<template>
    <div>
        <global-tables @handleAllSelect="handleAllSelect" @changePage="handleChangePage" :list="list" :total="total" :loading="loading" :columns="columns" :current="search.Page">
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <div>
                            <Button v-if="isAddBtn" class="features-btn" @click="handleBtnClick(null,'add')">
                                <Icon type="md-add" size="18" />
                                新建
                            </Button>
                            <Button v-if="isDelete" class="features-btn btn-auto-m" @click="handleBtnClick(null,'delete')">
                                <Icon class="btn btn-auto-m" type="md-trash" size="18" />
                                作废
                            </Button>
                        </div>
                    </div>
                    <div class="table-top-wrap-bottom">
                        <div>
                            <input type="text" class="style-input" style="width: 210px" @keyup.enter="handleSearch" v-model="search.keyword" placeholder="请输入配送单号 / 采购单号 / 供货商">
                            <i-input style="display:none"></i-input>
                        </div>
                        <div>
                            <Button icon="ios-search" @click="handleSearch" class="search-btn">搜索</Button>
                        </div>
                    </div>
                </div>
            </Form>
        </global-tables>
        <Modal :mask-closable="false" v-model="isModal" :title="ModalTitle" width="1100">
            <div v-if="isModal">
                <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                    <Row>
                        <i-col :lg="{ span: 8}">
                            <FormItem label="采购单" prop="OrderID">
                                <AsyncSelect :currentModel="formItem.OrderID" :url="'PurchaseOrders/WaitDelivery'" :value="'OrderID'" :typeOf="'purchase'" :theWay="'get'" @setDictionaries="setDictionaries"></AsyncSelect>
                            </FormItem>
                        </i-col>
                        <i-col :lg="{ span: 8}">
                            <FormItem label="配送门店" prop="ShopID">
                                <AsyncSelect :currentModel="formItem.ShopID" :url="'Shop/GetShopList'" :value="'ShopID'" :typeOf="'store'" :theWay="'get'" @setDictionaries="setDictionaries"></AsyncSelect>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 22}">
                            <FormItem label="商品详情">
                                <Table max-height="395" :columns="projuctColumns" :data="projuctList"></Table>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 22}">
                            <FormItem label="备注" prop="Remark">
                                <i-input type="textarea" v-model="formItem.Remark" placeholder="请输入备注"></i-input>
                            </FormItem>
                        </i-col>
                    </Row>
                </Form>
            </div>
            <div slot="footer">
                <Button size="large" @click="handleClose">取消</Button>
                <Button type="primary" size="large" @click="handleSubmit('formItem')">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
/**
 *  配送单列表
 */
import { cyclicRouting } from "@/util";
import { getModulePermission } from "@/api/user";
import GlobalTables from "@/components/GlobalTables";
import AsyncSelect from "@/components/AsyncSelect";
import Api from "./service";

export default {
    name: "PurchaseDelivery",
    components: {
        GlobalTables,
        AsyncSelect
    },
    data() {
        const validatorOrderID = (rule, value, callback) => {
            setTimeout(() => {
                if (this.formItem.OrderID == "" || !this.formItem.OrderID) {
                    callback(new Error("请选择采购单"));
                } else {
                    callback();
                }
            }, 100);
        };
        const validatorShopID = (rule, value, callback) => {
            setTimeout(() => {
                if (this.formItem.ShopID == "" || !this.formItem.ShopID) {
                    callback(new Error("请选择门店"));
                } else {
                    callback();
                }
            }, 100);
        };
        return {
            list: [],
            total: 0,
            itemId: 0,
            loading: true,
            isAddBtn: false,
            isDelete: false,
            isModal: false,
            allSelectArr: null,
            ModalTitle: "新建配送单",
            formItem: this.initFormItem(),
            search: {
                keyword: "",
                pageindex: 1,
                pagesize: 10
            },
            ruleValidate: {
                OrderID: [
                    {
                        required: true,
                        validator: validatorOrderID
                    }
                ],
                ShopID: [
                    {
                        required: true,
                        validator: validatorShopID
                    }
                ]
            },
            projuctColumns: [
                {
                    title: "商品图片",
                    render: (h, params) => {
                        const { PictureSmall } = params.row;
                        return h("div", [
                            h("Avatar", {
                                props: {
                                    src: PictureSmall,
                                    shape: "square",
                                    size: "large"
                                },
                                style: {
                                    margin: "5px 0"
                                }
                            })
                        ]);
                    }
                },
                {
                    title: "商品名称",
                    key: "PName"
                },
                {
                    title: "商品规格",
                    key: "PSName"
                },
                {
                    title: "采购数量",
                    key: "Count"
                },
                {
                    title: "剩余数量",
                    key: "Surplus"
                },
                {
                    title: "配送数量",
                    render: (h, params) => {
                        return h("div", [
                            h("InputNumber", {
                                props: {
                                    value: params.row.CountOrder,
                                    max: params.row.Surplus,
                                    min: 0
                                },
                                on: {
                                    "on-change": e => {
                                        this.projuctList[
                                            params.index
                                        ].CountOrder = e;
                                        this.projuctList[params.index].Money =
                                            e * params.row.Cost;
                                        this.projuctList.splice(
                                            params.index,
                                            0
                                        );
                                    }
                                }
                            })
                        ]);
                    }
                },
                {
                    title: "成本",
                    key: "Cost"
                },
                {
                    title: "金额",
                    render: (h, params) => {
                        return h("div", [h("span", {}, params.row.Money)]);
                    }
                }
            ],
            projuctList: [],
            /* 表头 */
            columns: [
                {
                    type: "selection",
                    width: 60,
                    align: "center"
                },
                {
                    title: "配送单号",
                    width: 160,
                    key: "DeliveryCode"
                },
                {
                    title: "采购单号",
                    key: "OrderCode"
                },
                {
                    title: "供货商",
                    key: "SupplierName"
                },
                {
                    title: "配送门店",
                    key: "ShopName"
                },
                {
                    title: "数量",
                    key: "TotalCount"
                },
                {
                    title: "金额",
                    key: "TotalPrice"
                },
                {
                    title: "状态",
                    width: 80,
                    render: (h, params) => {
                        const { State } = params.row;
                        if (State == 0) {
                            return h("div", [
                                h("Badge", {
                                    props: {
                                        status: "processing",
                                        text: "创建"
                                    }
                                })
                            ]);
                        } else if (State == 1) {
                            return h("div", [
                                h("Badge", {
                                    props: {
                                        status: "success",
                                        text: "收货"
                                    }
                                })
                            ]);
                        } else if (State == 2) {
                            return h("div", [
                                h("Badge", {
                                    props: {
                                        status: "error",
                                        text: "差异单"
                                    }
                                })
                            ]);
                        }
                    }
                },
                {
                    title: "操作",
                    width: 100,
                    align: "center",
                    render: (h, params) => {
                        const { isEdit } = this;
                        const { State } = params.row;
                        return h("div", [
                            isEdit &&
                                State == 0 &&
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "primary",
                                            size: "small"
                                        },
                                        style: {
                                            background: "#5ab1ef",
                                            border: "none",
                                            marginRight: "5px"
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(
                                                    params.row,
                                                    "edit"
                                                );
                                            }
                                        }
                                    },
                                    "修改"
                                )
                        ]);
                    }
                }
            ]
        };
    },
    methods: {
        /* 关闭对话框 */
        handleClose() {
            this.isModal = false;
        },
        /* 提交 */
        handleSubmit(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    const { projuctList } = this;
                    let data = this.formItem;
                    data.details = projuctList
                        .filter(item => {
                            return item.CountOrder > 0;
                        })
                        .map(item => {
                            item.ShopID = this.formItem.ShopID;
                            item.OrderID = this.formItem.OrderID;
                            delete item.ID;
                            delete item.PictureSmall;
                            return item;
                        });
                    data.ID = this.itemId;
                    Api.addTablesItem(data).then(res => {
                        if (res.state == "success") {
                            this.$Message.success("操作成功");
                            this.loading = true;
                            this.isModal = false;
                            this.getTablesListData();
                        } else {
                            this.$Message.error(res.message);
                        }
                    });
                }
            });
        },
        /* 采购单选择 */
        setDictionaries(item, value) {
            this.formItem[value] = item.ID + "";
            if (item.SupplierID) {
                this.formItem.SupplierID = item.SupplierID + "";
                Api.getProjuctDetail({
                    orderid: item.ID
                }).then(res => {
                    this.projuctList = res.data;
                    for (let item in this.projuctList) {
                        this.projuctList[item].CountOrder = 0;
                    }
                });
            } else if (item.ShopCode && this.projuctList.length > 0) {
                this.formItem.ShopCode = item.ShopCode;
                for (let item in this.projuctList) {
                    this.projuctList[item].ShopID = this.formItem.ShopID;
                }
            }
        },
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            Api.getTablesList(data).then(res => {
                this.list = res.data.rows;
                this.loading = false;
                this.total = res.data.records;
            });
        },
        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        /* 对话框 */
        handleBtnClick(item, type) {
            if (type == "edit" || type == "add") {
                this.itemId = 0;
                this.isModal = true;
                if (type == "edit") {
                    this.ModalTitle = "修改配送单";
                    Api.getItemInfo({
                        id: item.ID
                    }).then(res => {
                        this.itemId = item.ID;
                        this.formItem.OrderID = res.data.OrderID + "";
                        this.formItem.ShopID = res.data.ShopID + "";
                        this.formItem.Remark = res.data.Remark;
                        const { Details } = res.data;
                        for (let item in Details) {
                            Details[item].Money =
                                Details[item].Cost * Details[item].CountOrder;
                        }
                        this.projuctList = Details;
                    });
                } else {
                    this.ModalTitle = "新建配送单";
                    this.projuctList = [];
                    this.formItem = this.initFormItem();
                }
            } else if (type === "delete") {
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要作废吗`,
                        onOk: () => {
                            Api.deleteItem({
                                ids: this.allSelectArr
                            }).then(res => {
                                if (res.state == "success") {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = "";
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info("取消成功");
                        }
                    });
                } else {
                    this.$Message.error("请先选择需要操作的记录");
                }
            }
        },
        /* 表单数据 */
        initFormItem() {
            return {
                OrderID: "",
                SupplierID: ""
            };
        },
        /* 表格分页方法 */
        handleChangePage(type, page) {
            this.loading = true;
            if (type == "page") {
                this.search.pageindex = page;
                this.getTablesListData();
            } else {
                this.search.pagesize = page;
                this.getTablesListData();
            }
        },
        /* 复选框选中 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(",");
            }
            arr = arr.join(",");
            this.allSelectArr = arr;
        }
    },
    mounted() {
        /* 获取菜单的id */
        cyclicRouting(
            JSON.parse(sessionStorage.getItem("user")).menuList,
            this.$route,
            id => {
                /* 按钮权限请求 */
                getModulePermission({
                    roleid: JSON.parse(sessionStorage.getItem("user")).roleid,
                    moduleid: id
                }).then(res => {
                    /* 按钮权限赋值 */
                    for (let item in res.data) {
                        if (res.data[item].name == "add") {
                            this.isAddBtn = true;
                        } else if (res.data[item].name == "delete") {
                            this.isDelete = true;
                        } else if (res.data[item].name == "edit") {
                            this.isEdit = true;
                        }
                    }
                    /* 列表请求 */
                    this.getTablesListData();
                });
            }
        );
    }
};
</script>

<style>
</style>
